using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ReplacePerelivController : MonoBehaviour
{
	public static ReplacePerelivController instance;

	private ADSLocation currentWindow = ADSLocation.Start;

	private Texture2D _image;

	private string _adUrl;

	private static int _amountToShow = -1;

	private long _timeSuspended;

	private bool _showIndicator;

	private bool _showBannerMoney;

	private int _indexPromo = -1;

	[HideInInspector]
	public bool pvpMapsScreenDelay = true;

	public GameObject Container;

	public UISprite Bg;

	public UITexture TextureImage;

	public GameObject successPerelivObj;

	public static bool needShowButtonGold;

	public static bool disableButtonPromo;

	private IEnumerator _updateWaite;

	private bool _readyToShow = true;

	private bool _showReplace = true;

	private bool _force;

	private string keyAlreadyShowedPromo = "keyAlreadyShowedPromo";

	private string keyShowAgainIndex = "keyShowAgainIndex";

	private bool DataLoaded
	{
		get
		{
			return _image != null && _adUrl != null;
		}
	}

	private bool DataLoading { get; set; }

	public bool AlreadyShowedPromo
	{
		get
		{
			string key = keyAlreadyShowedPromo;
			try
			{
				return BCWStorage.Get<bool>(key);
			}
			catch
			{
				return false;
			}
		}
	}

	public static event Action<bool> bannerNeedShow;

	private void StateBannerButton()
	{
		if (!_showReplace)
		{
			disableButtonPromo = true;
		}
		else if (GetIndexPromo(true) == -1)
		{
			disableButtonPromo = true;
		}
	}

	private bool ShowTotal()
	{
		_amountToShow++;
		return PromoActionManager.ReplacePereliv != null && _amountToShow < PromoActionManager.ReplacePereliv.ShowTimesTotal;
	}

	private void DestroyImages()
	{
		if (_image != null)
		{
			UnityEngine.Object.Destroy(_image);
			_image = null;
		}
		if (TextureImage != null)
		{
			TextureImage.mainTexture = null;
		}
		Resources.UnloadUnusedAssets();
	}

	public string GetImageUrl()
	{
		if (_indexPromo == -1 || _indexPromo >= PromoActionManager.ReplacePereliv.imageUrls.Count)
		{
			return string.Empty;
		}
		return PromoActionManager.ReplacePereliv.imageUrls[_indexPromo];
	}

	private int GetIndexPromo(bool withMoney = false)
	{
		if (PromoActionManager.ReplacePereliv.imageUrls.Count > 0)
		{
			if (AlreadyShowedPromo)
			{
				return -1;
			}
			for (int i = 0; i < PromoActionManager.ReplacePereliv.imageUrls.Count; i++)
			{
				if (_indexPromo == -1)
				{
					_indexPromo = UnityEngine.Random.Range(0, PromoActionManager.ReplacePereliv.imageUrls.Count);
					continue;
				}
				_indexPromo++;
				if (_indexPromo >= PromoActionManager.ReplacePereliv.imageUrls.Count)
				{
					_indexPromo = 0;
				}
			}
			return _indexPromo;
		}
		return -1;
	}

	private bool PromoWithMoney()
	{
		if (_indexPromo >= 0 && ((PromoActionManager.ReplacePereliv.countCash.Count > _indexPromo && PromoActionManager.ReplacePereliv.countCash[_indexPromo] > 0) || (PromoActionManager.ReplacePereliv.countGold.Count > _indexPromo && PromoActionManager.ReplacePereliv.countGold[_indexPromo] > 0)))
		{
			return true;
		}
		return false;
	}

	public bool ShowButton()
	{
		if (PromoActionManager.jsonReaded)
		{
			return _showReplace && PromoWithMoney();
		}
		return false;
	}

	public void OpenBunnerButton()
	{
		if (_showReplace && PromoWithMoney())
		{
			ShowPromo(true);
			currentWindow = ADSLocation.Start;
			_force = true;
		}
		else
		{
			StartCoroutine(MarketControllerUI.instance.ShowBank());
		}
	}

	public void LoadPerelivData(bool withMoney = false)
	{
		if (_updateWaite == null)
		{
			_updateWaite = UpdateWait();
			StartCoroutine(_updateWaite);
		}
		if (DataLoading)
		{
			BCWDebug.LogWarning("ReplaceAdmobPerelivController: data is already loading. returning...");
			return;
		}
		StateBannerButton();
		if (_image != null)
		{
			UnityEngine.Object.Destroy(_image);
		}
		_adUrl = null;
		int indexPromo = GetIndexPromo(withMoney);
		if (indexPromo != -1)
		{
			if (withMoney)
			{
				controllerMenu.thisScript.showIndicator();
				_showIndicator = true;
			}
			StartCoroutine(LoadDataCoroutine(indexPromo));
		}
	}

	private string GetImageURLForOurQuality(string urlString)
	{
		string value = string.Empty;
		if (Screen.height >= 500)
		{
			value = "-Medium";
		}
		if (Screen.height >= 900)
		{
			value = "-Hi";
		}
		urlString = urlString.Insert(urlString.LastIndexOf("."), value);
		return urlString;
	}

	private IEnumerator LoadDataCoroutine(int index)
	{
		Save.SaveLong("AdvLoadingStart", EventX3Manager.CurrentUnixTime);
		DataLoading = true;
		WWW imageRequest = new WWW(GetImageURLForOurQuality(PromoActionManager.ReplacePereliv.imageUrls[index]));
		yield return imageRequest;
		if (!string.IsNullOrEmpty(imageRequest.error))
		{
			DataLoading = false;
			BCWDebug.LogWarning("ReplaceAdmobPerelivController: error loading image. returning...");
			if (_showIndicator)
			{
				controllerMenu.thisScript.hideIndicator();
			}
		}
		else if (!imageRequest.texture)
		{
			DataLoading = false;
			BCWDebug.LogWarning("ReplaceAdmobPerelivController: imageRequest.texture = null. returning...");
			if (_showIndicator)
			{
				controllerMenu.thisScript.hideIndicator();
			}
		}
		else if (imageRequest.texture.width < 20)
		{
			DataLoading = false;
			BCWDebug.LogWarning("ReplaceAdmobPerelivController: imageRequest.texture is dummy. returning...");
			if (_showIndicator)
			{
				controllerMenu.thisScript.hideIndicator();
			}
		}
		else
		{
			_image = imageRequest.texture;
			_adUrl = PromoActionManager.ReplacePereliv.adUrls[index];
			DataLoading = false;
		}
	}

	public void CloseBanner()
	{
		Container.SetActive(false);
		if (ReplacePerelivController.bannerNeedShow != null)
		{
			ReplacePerelivController.bannerNeedShow(true);
		}
		StartCoroutine(TimerReplace());
	}

	public void OpenUrl()
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		dictionary.Add("Click and Show", "Click");
		dictionary.Add("Networks", FlurryWrapper.GetCurrentNetworkType());
		if (_indexPromo == 0)
		{
			dictionary.Add("Mobile", "Click");
		}
		else
		{
			dictionary.Add("PC", "Click");
		}
		FlurryWrapper.LogEvent(FlurryWrapper.EV_ADV_BANER, dictionary);
		Application.OpenURL(_adUrl);
		Container.SetActive(false);
		DestroyImages();
		needShowButtonGold = false;
		if (ReplacePerelivController.bannerNeedShow != null)
		{
			ReplacePerelivController.bannerNeedShow(false);
		}
		_showBannerMoney = true;
	}

	public void ShowAgainInit()
	{
		int showAgainIndex = PromoActionManager.ReplacePereliv.showAgainIndex;
		if (showAgainIndex == -1)
		{
			return;
		}
		int num = 0;
		try
		{
			num = BCWStorage.Get<int>(keyShowAgainIndex);
		}
		catch
		{
			BCWStorage.Set(keyShowAgainIndex, -1);
			num = -1;
		}
		if (num < showAgainIndex)
		{
			int num2 = 0;
			foreach (string imageUrl in PromoActionManager.ReplacePereliv.imageUrls)
			{
				if (num2 < PromoActionManager.ReplacePereliv.showAgainList.Count)
				{
					if (PromoActionManager.ReplacePereliv.showAgainList[num2])
					{
						string key = keyAlreadyShowedPromo;
						BCWStorage.Set(key, false, true);
					}
					num2++;
					continue;
				}
				break;
			}
			BCWStorage.Set(keyShowAgainIndex, showAgainIndex);
		}
		CheckStatusReplace();
	}

	private void CheckStatusReplace()
	{
		_showReplace = false;
		if (PromoActionManager.ReplacePereliv.enabled && (PromoActionManager.ReplacePereliv.ShowToNew || !PromoActionManager.NewUser(PromoActionManager.ReplacePereliv.newUserStatusDays)) && (PromoActionManager.ReplacePereliv.ShowToPaying || !PromoActionManager.PayingUser()) && PromoActionManager.ReplacePereliv.ShowTimesTotal != 0 && !BCWStorage.Get<bool>(keyAlreadyShowedPromo))
		{
			_showReplace = true;
		}
	}

	public void GiveMoney()
	{
		if (_showBannerMoney)
		{
			_showBannerMoney = false;
			int num = 0;
			int num2 = 0;
			if (PromoActionManager.ReplacePereliv.countCash.Count > _indexPromo)
			{
				num = PromoActionManager.ReplacePereliv.countCash[_indexPromo];
			}
			if (PromoActionManager.ReplacePereliv.countGold.Count > _indexPromo)
			{
				num2 = PromoActionManager.ReplacePereliv.countGold[_indexPromo];
			}
			settings.CathedExeptions += num;
			settings.CathedWarnings += num2;
			settings.SaveCathedExeptionsToStorager();
			string key = keyAlreadyShowedPromo;
			BCWStorage.Set(key, true, true);
			CheckStatusReplace();
			if (num > 0 || num2 > 0)
			{
				InAppShop.instance.playSoundBuyCoins();
				successPerelivObj.SetActive(true);
			}
			StateBannerButton();
		}
	}

	public void CloseSuccessMessage()
	{
		successPerelivObj.SetActive(false);
	}

	private void OnApplicationPause(bool pauseStatus)
	{
		if (!pauseStatus)
		{
			GiveMoney();
		}
	}

	private IEnumerator ChangeTexture()
	{
		yield return new WaitForSeconds(0.1f);
		if (_image != null)
		{
			TextureImage.width = Bg.width;
			float aspectTexture = (float)_image.width / (float)_image.height;
			TextureImage.height = (int)((float)TextureImage.width / aspectTexture);
			TextureImage.mainTexture = _image;
		}
	}

	public bool ShowWindows()
	{
		if (_readyToShow || _force)
		{
			_readyToShow = false;
			_force = false;
			if (_showIndicator)
			{
				controllerMenu.thisScript.hideIndicator();
			}
			long num = Load.LoadLong("AdvLoadingStart");
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			dictionary.Add("Click and Show", "Show");
			if (num != 0L)
			{
				dictionary.Add("Upload time", FlurryWrapper.AdvBanerLoadingTime(EventX3Manager.CurrentUnixTime - num));
				Save.SaveLong("AdvLoadingStart", 0L);
			}
			if (_indexPromo == 0)
			{
				dictionary.Add("Mobile", "Show");
			}
			else
			{
				dictionary.Add("PC", "Show");
			}
			FlurryWrapper.LogEvent(FlurryWrapper.EV_ADV_BANER, dictionary);
			if (BCWDebug.isDebugBuild)
			{
				BCWDebug.Log("Show Windows Promo");
			}
			_amountToShow++;
			Container.SetActive(true);
			StartCoroutine(ChangeTexture());
			needShowButtonGold = true;
			return true;
		}
		return false;
	}

	private void Awake()
	{
		instance = this;
		if (PromoActionManager.jsonReaded)
		{
			Init();
		}
	}

	public void Init()
	{
		ShowAgainInit();
		CheckStatusReplace();
	}

	public IEnumerator TimerReplace()
	{
		yield return new WaitForSeconds(PromoActionManager.ReplacePereliv.showFrequency);
		_readyToShow = true;
	}

	public void ShowPromo(bool withMoney = false)
	{
		if (_updateWaite == null)
		{
			_updateWaite = UpdateWait();
			StartCoroutine(_updateWaite);
		}
		if (withMoney)
		{
			if (!PromoWithMoney() || !DataLoaded)
			{
				_image = null;
				_adUrl = null;
				DataLoading = false;
				LoadPerelivData(withMoney);
			}
			if (_updateWaite != null)
			{
				StopCoroutine(_updateWaite);
			}
			_updateWaite = UpdateWait();
			StartCoroutine(_updateWaite);
		}
		else if (!DataLoaded && !DataLoading && ShowTotal())
		{
			LoadPerelivData(withMoney);
		}
	}

	private IEnumerator UpdateWait()
	{
		while (true)
		{
			if (SceneManager.GetActiveScene().name != "Lobby" || (X3AndBonusInMenu.instance != null && !X3AndBonusInMenu.instance.x3Event) || (X3AndBonusInMenu.instance != null && !X3AndBonusInMenu.instance.bonusEvent) || MarketControllerUI.instance.MarketActive())
			{
				if (_showIndicator)
				{
					controllerMenu.thisScript.hideIndicator();
				}
				yield return null;
				continue;
			}
			if (((currentWindow != GetCurrentInterfaceLocation() && GetCurrentInterfaceLocation() != 0) || _force) && _showReplace)
			{
				if (!DataLoaded)
				{
					yield return new WaitForSeconds(0.5f);
					continue;
				}
				if (ShowWindows())
				{
					currentWindow = GetCurrentInterfaceLocation();
				}
			}
			yield return null;
		}
	}

	private ADSLocation GetCurrentInterfaceLocation()
	{
		if (controllerMenu.thisScript != null && controllerMenu.thisScript.panelMainMenu.gameObject.activeSelf)
		{
			return ADSLocation.Lobby;
		}
		return ADSLocation.None;
	}
}
